//
//  GroupInfoViewController.m
//  SouthChina
//
//  Created by kc on 15/7/15.
//  Copyright (c) 2015年 科创. All rights reserved.
//

#import "GroupInfoViewController.h"
#import "UnitView.h"
#import "ContactDao.h"
#import "Contact.h"
#import "selectMemberViewController.h"
#import "MessageSessionDao.h"
#import "ABookViewController.h"
#import "DataDictDao.h"
#import "ShowMemberViewController.h"
#import "QRcodeViewController.h"
#import "EditGroupImgViewController.h"
#import "selectLabelViewController.h"

@interface GroupInfoViewController ()<UnitViewDelegate>
{
    Contact * contact;
    NSString *sTitle;
    NSString *sCreateUser; //群创建者

}
@property (strong, nonatomic) IBOutlet UIButton *btqrcode;
@property (strong, nonatomic) IBOutlet UILabel *groupnumber;
@property (strong, nonatomic) IBOutlet UISwitch *btswitch;
@property (strong, nonatomic) IBOutlet UIView *grptagsView; //群标签

@property (strong, nonatomic) IBOutlet UILabel *Groupname;//群名称

@property (strong, nonatomic) IBOutlet UnitView *groupUser;
@property (strong, nonatomic) IBOutlet UIButton *btOperate;

@property (strong, nonatomic) IBOutlet UILabel *labelset;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *btVerconstraint;
@property (strong, nonatomic) IBOutlet UIImageView *groupImg;//群头像

@property (strong, nonatomic) NSMutableSet *groupuserarr;//群成员
@property (strong, nonatomic) UIView *bodyView;//主视图
@property (strong, nonatomic) NSMutableSet *selecteduser;//选择的群成员
@property (strong, nonatomic)UILabel *taglabel1;
@property (strong, nonatomic)UILabel *taglabel2;
@property (strong, nonatomic)UILabel *taglabel3;
@property (strong, nonatomic)UIButton *btaddtag;
@end



@implementation GroupInfoViewController
@synthesize groupid,qrCodeImage;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(contactMessage:) name:CONTACT_CHANGE_BROADCAST object:nil];
    }
    return self;
}

- (void)contactMessage:(NSNotification *)notification{
    
    NSDictionary* msg = [notification object];
    NSString * pass_sessionId = [msg objectForKey:@"sessionID"];
    NSString * pass_businessId = [msg objectForKey:@"businessId"];
    NSString *thisSessId = [NSString stringWithFormat:@"%@_%@",MESSAGE_TYPE_P2G,groupid];
    
    //改群名称
    if ([@"updateGrpName" isEqualToString:[msg objectForKey:@"businessId"]]) {
        if ([thisSessId isEqualToString:pass_sessionId]) {
            MessageSession *session = [MessageSessionDao queryMsgSessionById:thisSessId];
            self.Groupname.text=session.title;
            sTitle =session.title;
        }
    }
    //解散群组或者删除好友，则要关闭当前界面
    else if(([@"dropGrp" isEqualToString:pass_businessId]||[@"endFriendship" isEqualToString:pass_businessId])
            &&[thisSessId isEqualToString:pass_sessionId]){
        //[self.navigationController popViewControllerAnimated:YES];
        ABookViewController * bookcontrol = [[ABookViewController alloc] init];
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:bookcontrol animated:NO];
        
    }
    
}

//将dictdataId 转换为 dictdataValue
-(NSString *) getlabelname:(NSString *)dictdataId
{
    if ([dictdataId isEqualToString:@""]) {
        return @"";
    }
    else
    {   //80,81, 转换为 ‘80’,'81'
        NSArray *list=[dictdataId componentsSeparatedByString:@","];
        NSMutableString *skeylist = [[NSMutableString alloc] initWithString:@""];
        NSMutableString *sreturnlist = [[NSMutableString alloc] initWithString:@""];
        for(NSInteger i = 0;i<list.count;i++)
        {
            if(![list[i] isEqualToString:@""])
            {
                if(i==0)
                    [skeylist insertString:[NSString stringWithFormat:@"'%@'",list[i]] atIndex:0];
                else
                    [skeylist insertString:[NSString stringWithFormat:@"'%@',",list[i]] atIndex:0];
            }
            
        }
        NSLog(@"sreturnlist:%@",skeylist);
        NSString *sql = [NSString stringWithFormat:@"where dicttypeId ='8' and dictdataId in (%@)",skeylist];
        NSMutableArray *allLabeData = [DataDictDao queryDataDict:sql];
        for(NSInteger i = 0;i<allLabeData.count;i++)
        {
            DataDict * dataDict = [allLabeData objectAtIndex:i];
            if(i==0)
                [sreturnlist insertString:[NSString stringWithFormat:@"%@",dataDict.dictdataValue] atIndex:0];
            else
                [sreturnlist insertString:[NSString stringWithFormat:@"%@,",dataDict.dictdataValue] atIndex:0];
        }
        NSLog(@"数据库转换为：%@",sreturnlist);
        return  sreturnlist;
    }
}

-(void) Setlabellist:(NSString *)dictdataId groupType:(NSString *)grptype
{
    NSLog(@"&&&&&&&&& %@",dictdataId);
    if (![dictdataId isEqualToString:@""])
    {   //80,81, 转换为 ‘80’,'81'
         NSLog(@"&&&&&&&&&VVVVVVVVVVVVVVVVVV %@",dictdataId);
        NSArray *list=[dictdataId componentsSeparatedByString:@","];
        NSMutableString *skeylist = [[NSMutableString alloc] initWithString:@""];
        for(NSInteger i = 0;i<list.count;i++)
        {
            if(![list[i] isEqualToString:@""])
            {
                if(i==0)
                    [skeylist insertString:[NSString stringWithFormat:@"'%@'",list[i]] atIndex:0];
                else
                    [skeylist insertString:[NSString stringWithFormat:@"'%@',",list[i]] atIndex:0];
            }
            
        }
        NSLog(@"sreturnlist:%@",skeylist);
        NSString *sql = [NSString stringWithFormat:@"where dicttypeId ='8' and dictdataName in (%@)",skeylist];
        [self reSetGroupLable:[DataDictDao queryDataDict:sql] groupType:grptype];
        
    }
    else
    {
         NSLog(@"&&&&&&&&&XXXXXXXXXXXXXXXX %@",dictdataId);
        if ([grptype isEqualToString:@"0"]) {
            _taglabel1.hidden = YES;
            _taglabel2.hidden = YES;
            _taglabel3.hidden = YES;
            _btaddtag.hidden = NO;
            _btaddtag.center = CGPointMake(95, 30);
            NSLog(@"&&&&&&&&&XYYYYYYYYYYYY %@",dictdataId);
           }
        
    }
}

-(void)reSetGroupLable:(NSArray*)arrlist groupType:(NSString *)grpType
{
    _taglabel1.hidden = YES;
    _taglabel2.hidden = YES;
    _taglabel3.hidden = YES;
    _btaddtag.hidden = YES;
    if(arrlist.count == 0 && [grpType isEqualToString:@"0"])
    {
        _btaddtag.center = CGPointMake(95, 30);
        _btaddtag.hidden = NO;
        return;
    }
    
    for(int i = 0;i<arrlist.count;i++)
    {
        //最多显示3个
        if(i>2)
            break;
        
        DataDict *dict = arrlist[i];
        if(i==0)
            _taglabel1.text = dict.dictdataValue;
        else if(i==1)
            _taglabel2.text =dict.dictdataValue;
        else if(i==2)
            _taglabel3.text =dict.dictdataValue;
    }
    if(arrlist.count==0)
    {
       _btaddtag.center = CGPointMake(95, 30);
    }
    else if(arrlist.count==1)
    {
        _taglabel1.hidden = NO;
        _btaddtag.center = CGPointMake(160, 30);
    }
    else if(arrlist.count==2)
    {
        _taglabel1.hidden = NO;
        _taglabel2.hidden = NO;
        _btaddtag.center = CGPointMake(235, 30);
    }
    else if(arrlist.count>=3)
    {
        _taglabel1.hidden = NO;
        _taglabel2.hidden = NO;
        _taglabel3.hidden = NO;
        _btaddtag.center = CGPointMake(290, 30);
    }
    //grpType 为 0：我管理的群，才有权限重置群标签
    if ([grpType isEqualToString:@"0"]) {
        _btaddtag.hidden = NO;
    }
}

//根据dictdataId获取DicData
-(NSMutableArray *) getlabelDictArr:(NSString *)dictdataId
{
    NSMutableArray *ArrList = [[NSMutableArray alloc] init];
    NSArray *list=[dictdataId componentsSeparatedByString:@","];
    NSMutableString *skeylist = [[NSMutableString alloc] initWithString:@""];
    for(NSInteger i = 0;i<list.count;i++)
    {
        if(![list[i] isEqualToString:@""])
        {
            if(i==0)
                [skeylist insertString:[NSString stringWithFormat:@"'%@'",list[i]] atIndex:0];
            else
                [skeylist insertString:[NSString stringWithFormat:@"'%@',",list[i]] atIndex:0];
        }
    }
    NSString *sql = [NSString stringWithFormat:@"where dicttypeId ='8' and dictdataName in (%@)",skeylist];
    NSLog(@"SQL    %@",sql);
    ArrList = [DataDictDao queryDataDict:sql];
    
    return  ArrList;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    //Do any additional setup after loading the view.
    //获取群信息：
    NSLog(@"groupid:%@",groupid);
    //创建人
    //creatUser = [contact getValue:@"CREATE_USER"];
    //20150724做修改，暂时contact表中字段create_user后台更新通讯录时没有更新这个字段，后面会优化更新这个字段，暂时通过接口queryGroupInfo查询群信息
    
    _bodyView = [[[NSBundle mainBundle] loadNibNamed:@"GroupInfoViewBody" owner:self options:nil] objectAtIndex:0];
    _bodyView.frame = (CGRect){0, TITLE_BAR_HEGIHT+YNEW,SCREEN_WIDTH, SCREEN_HEIGHT-TITLE_BAR_HEGIHT-YNEW};
    [self.view addSubview:_bodyView];
    
    [self addTitleBarWithBackBtn:@"群资料" needReturn:YES];
    
     _selectedLable = [[NSMutableSet alloc]init];
    
    sCreateUser = @"";
    //群头像增加点击事件
    _groupImg.userInteractionEnabled=YES;
    _groupImg.layer.masksToBounds = YES;
    _groupImg.layer.cornerRadius = 23;
    UITapGestureRecognizer *singleTap =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onClickImage)];
    [_groupImg addGestureRecognizer:singleTap];
    
    UILabel *labelhead = [[UILabel alloc]initWithFrame:CGRectMake(20, 20, 40, 20)];
    labelhead.text = @"标签:";
    labelhead.textAlignment = NSTextAlignmentLeft;
    labelhead.font = [UIFont systemFontOfSize:15.0f];
    [_grptagsView addSubview:labelhead];
    
    _taglabel1 = [[UILabel alloc]initWithFrame:CGRectMake(70, 12, 50, 36)];
    _taglabel1.textAlignment = NSTextAlignmentCenter;
    _taglabel1.font = [UIFont systemFontOfSize:12.0f];
    _taglabel1.backgroundColor = [UIColor colorWithRed:65.0f/255.0f green:105.0f/255.0f blue:225.0f/255.0f alpha:1.0f];
    _taglabel1.layer.cornerRadius = 15;
    _taglabel1.layer.masksToBounds = YES;
    _taglabel1.textColor = [UIColor whiteColor];
    [_grptagsView addSubview:_taglabel1];
    _taglabel1.hidden = YES;
    
    _taglabel2 = [[UILabel alloc]initWithFrame:CGRectMake(135, 12, 50, 36)];
    _taglabel2.textAlignment = NSTextAlignmentCenter;
    _taglabel2.font = [UIFont systemFontOfSize:12.0f];
    _taglabel2.backgroundColor = [UIColor colorWithRed:65.0f/255.0f green:105.0f/255.0f blue:225.0f/255.0f alpha:1.0f];
    _taglabel2.layer.cornerRadius = 15;
    _taglabel2.layer.masksToBounds = YES;
    _taglabel2.textColor = [UIColor whiteColor];
    [_grptagsView addSubview:_taglabel2];
    _taglabel2.hidden = YES;
    
    _taglabel3 = [[UILabel alloc]initWithFrame:CGRectMake(200, 12, 50, 36)];
    _taglabel3.textAlignment = NSTextAlignmentCenter;
    _taglabel3.font = [UIFont systemFontOfSize:12.0f];
    _taglabel3.backgroundColor = [UIColor colorWithRed:65.0f/255.0f green:105.0f/255.0f blue:225.0f/255.0f alpha:1.0f];
    _taglabel3.layer.cornerRadius = 15;
    _taglabel3.layer.masksToBounds = YES;
    _taglabel3.textColor = [UIColor whiteColor];
    [_grptagsView addSubview:_taglabel3];
    _taglabel3.hidden = YES;
    
    _btaddtag = [[UIButton alloc] initWithFrame:CGRectMake(265, 5, 50, 50)];
    [_btaddtag addTarget:self action:@selector(addtagbtn:) forControlEvents:UIControlEventTouchUpInside];
    [_btaddtag setTitle:@"" forState:UIControlStateNormal];
    [_btaddtag setBackgroundImage:[UIImage imageNamed:@"addmore.png"] forState:UIControlStateNormal];
    _btaddtag.hidden = YES;
    [_grptagsView addSubview:_btaddtag];
    
    //查询群信息接口 queryGroupInfo
    NSDictionary *map = @{@"groupId":groupid};
    if([_grouptype isEqualToString:TYPE_GROUP_PUTONG])//普通群
    {
        contact = [ContactDao getContactById:groupid];
        sTitle = contact.mNAME?contact.mNAME:@"";
        //群名称
        _Groupname.text = contact.mNAME?contact.mNAME:@"";
        //群头像
        NSURL *url= [NSURL URLWithString: [contact.mHEAD_IMG hasPrefix:@"http"]?contact.mHEAD_IMG:[NSString stringWithFormat:@"%@%@",DE.fileEngineeUrl,contact.mHEAD_IMG]];
        _groupImg.layer.masksToBounds = YES;
        _groupImg.layer.cornerRadius = 20;
        [_groupImg setImageWithURL:url placeholderImage:[UIImage imageNamed:@"empty_photo"]];
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [DE serverCall:@"queryGroupInfo" params:map callback:^(BOOL success, int code, NSString *desc, NSDictionary *data,NSDictionary*param) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            if(success)
            {
                NSMutableDictionary *dictionary = [data objectForKey:@"group"];
                sCreateUser = [dictionary objectForKey:@"createUser"];
                //20150724 群创建者显示解散群
                NSString *stags = [dictionary objectForKey:@"groupTags"]==nil?@"":[dictionary objectForKey:@"groupTags"];
                NSLog(@"XXXXXXXXXXXXXXstags %@",stags);
               if([[dictionary objectForKey:@"createUser"] isEqualToString:DE.userId])
                {
                    [_btOperate setTitle:@"解散群" forState:UIControlStateNormal];
                    [_btOperate setBackgroundColor:[UIColor redColor]];
                    _btOperate.tag=101;
                    [self Setlabellist:stags groupType:@"0"];
                }
                else
                {
                    [_btOperate setTitle:@"退群" forState:UIControlStateNormal];
                     [_btOperate setBackgroundColor:[UIColor redColor]];
                    _btOperate.tag=102;
                    [self Setlabellist:stags groupType:@"1"];
                }
                [_selectedLable addObjectsFromArray:[self getlabelDictArr:stags]];
            }
            else{
                [self showAlerHUD:@"查询群信息失败！"];
            }
        }];
        
        //切换按钮
        NSLog(@"usergrp:%@",contact.mID);
        NSLog(@"ACTIVATED:%@",contact.mIS_ACTIVATED);
        //暂时功能不支撑
        _btswitch.on = [@"0" isEqualToString:contact.mIS_ACTIVATED];
        //群成员初始化
        _groupUser.isAddButton =YES;
        _groupUser.isDoneButton = YES;
        
        //群成员多少人，根据groupid(ref_id查询群成员)，行政群和兴趣群只能通过接口从服务器上获取，本地数据库没有此数据
        NSString * where = [NSString stringWithFormat:@"where ref_id='%@' and operate='U'",groupid];
        _groupuserarr  = [[NSMutableSet alloc] initWithArray:[ContactDao getContactByWhere:where]];
        _groupnumber.text = [[NSString alloc] initWithFormat:@"  群成员（%lu人）" ,(unsigned long)_groupuserarr.count];
        for(Contact *contact0 in _groupuserarr)
        {
            [_groupUser addNewUnit:contact0];
        }
    }else if ([_grouptype isEqualToString:TYPE_GROUP_ORGANIZATION] || [_grouptype isEqualToString:TYPE_GROUP_INTEREST])//申请入群
    {
        NSLog(@"SSSSSSSSSSSSSSSSSSSSSSS");
        _groupuserarr  = [[NSMutableSet alloc] init];
        NSDictionary *map0 = @{@"groupId":groupid};
        //陌生群只返回管理员以上人员，其他人员不显示
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [DE serverCall:@"queryStrangeGrpInfo" params:map0 callback:^(BOOL success, int code, NSString *desc, NSDictionary *data,NSDictionary*param) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            if(success)
            {
                //群信息
                NSMutableDictionary *dictionary = [data objectForKey:@"userGroup"];
                NSString *stags = [dictionary objectForKey:@"groupTags"]==nil?@"":[dictionary objectForKey:@"groupTags"];
                [self Setlabellist:stags groupType:@"1"];
                [_selectedLable addObjectsFromArray:[self getlabelDictArr:stags]];
                sTitle = [dictionary objectForKey:@"groupName"]?[dictionary objectForKey:@"groupName"]:@"";
                //群名称
                _Groupname.text = sTitle;
                //群成员
                NSMutableSet *userarr = [data objectForKey:@"members"];
                NSEnumerator *enumerator = [userarr objectEnumerator];
                
                NSMutableDictionary *dictionarytmp  = [enumerator nextObject];
                while (dictionarytmp != nil) {
                    NSLog(@"memberId:%@",[dictionarytmp objectForKey:@"memberId"]);
                    Contact *contactTmp = [[Contact alloc] init];
                    contactTmp.mID = [dictionarytmp objectForKey:@"memberId"];
                    contactTmp.mHEAD_IMG = [dictionarytmp objectForKey:@"headImg"];
                    contactTmp.mNAME = [dictionarytmp objectForKey:@"memberName"];
                    [_groupuserarr addObject:contactTmp];
                    NSLog(@"%lu",_groupuserarr.count);
                    dictionarytmp  = [enumerator nextObject];
                }
                _groupnumber.text = [[NSString alloc] initWithFormat:@"  群管理员（%lu人）" ,(unsigned long)_groupuserarr.count];
                for(Contact *contact0 in _groupuserarr)
                {
                    NSLog(@"####################");
                    [_groupUser addNewUnit:contact0];
                }
            }
            else{
                [self showAlerHUD:@"查询群信息失败！"];
            }
        }];

        [_btOperate setTitle:@"申请入群" forState:UIControlStateNormal];
         [_btOperate setBackgroundColor:[UIColor colorWithRed:0.0f/255.0f green:131.0f/255.0f blue:255.0f/255.0f alpha:1.0f]];
        _btOperate.tag=103;
        _btswitch.hidden = YES;
        _labelset.hidden = YES;
        _btVerconstraint.constant = -43;
        
    }
    
    UIImageView *qrImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30,30)];
    qrImage.image = [UIImage imageNamed:@"二维码.png"];
    //按钮上增加图片
    [_btqrcode addSubview:qrImage];
    
    //群二维码
    qrCodeImage = [[UIImageView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH)/2-100, _groupUser.frame.origin.y+20, 200, 200)];
    [_bodyView addSubview:qrCodeImage];
    
    _groupUser = [_groupUser initWithFrame:_groupUser.frame];
    _groupUser.isDeleteable = NO;
    _groupUser.delegate = self;
    _selecteduser = [[NSMutableSet alloc] init];
}


-(void)addtagbtn:(id)sender
{
    NSLog(@"添加群标签");
    selectLabelViewController * select = [[selectLabelViewController alloc] init];
    
    select.selectedLable  = _selectedLable;
    select.sLableType = RESET_GROUPLABLE;
    select.groupId = groupid;
    [kAppDelegate.iCSDrawerController.navigationController pushViewController:select animated:NO];
    
}
-(void) onClickImage
{
    NSLog(@"点击图片事件");
    if([_grouptype isEqualToString:TYPE_GROUP_PUTONG])//普通群
    {
         if([sCreateUser isEqualToString:DE.userId]) //只有管理者才可以修改群图像和群名称
         {
             EditGroupImgViewController * editImgview = [[EditGroupImgViewController alloc]init];
             editImgview.groupId = groupid;
             [kAppDelegate.iCSDrawerController.navigationController pushViewController:editImgview animated:NO ];
         }
    }
    
}

-(void)getJoinGrpQrCode{
    
    NSDictionary *map = @{@"groupId":groupid};
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [DE serverCall:@"getJoinGrpQrCode" params:map callback:^(BOOL success, int code, NSString *desc, NSDictionary *data,NSDictionary*param) {
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if(success)
        {
            [self setQrCode:[data objectForKey:@"qrCodeSrc"]];
        }
        else{
            [self showAlerHUD:@"获取群组二维码失败！"];
        }
    }];
}

-(void)setQrCode:(NSString *)str
{
    QRcodeViewController *qrcodeimg = [[QRcodeViewController alloc] init];
    NSLog(@"URL:%@",str);
    qrcodeimg.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    if ([[[UIDevice currentDevice] systemVersion] floatValue]>=8.0) {
       qrcodeimg.modalPresentationStyle=UIModalPresentationOverCurrentContext;
    }else{
        self.modalPresentationStyle=UIModalPresentationCurrentContext;
   }
    qrcodeimg.strurl = str;
    [self presentViewController:qrcodeimg animated:YES completion:^{
        NSLog(@"present成功，从ViewController切换到QRcodeViewController");}];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//点击单元事件
- (void) extendCellTouched:(UnitCell *)unitCell
{
    
    if(unitCell.tag == ADDTAG)
    {
        selectMemberViewController * selectMember = [[selectMemberViewController alloc] init];
        selectMember.selectedContact = _selecteduser;
        selectMember.CreateType =  CREATETYPE_ADDGROUP;//添加群成员
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:selectMember animated:NO];
    }
    else
    {
      NSLog(@"展示群成员");
      [self removeThisSeesion];
      ShowMemberViewController *showusertalbe = [[ShowMemberViewController alloc] init];
        if([_grouptype isEqualToString:TYPE_GROUP_PUTONG])//普通群
        {
            showusertalbe.CreateType = SHOW_USER;
            showusertalbe.curOrgContact = contact;
        }else //行政群或者兴趣群
        {
            showusertalbe.groupuserlist = _groupuserarr;
            showusertalbe.CreateType = SHOW_ADMIN;
        }
        
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:showusertalbe animated:NO];
    }
}


- (IBAction)btqrcodeClick:(id)sender
{
   [self getJoinGrpQrCode];
}

//屏蔽消息切换事件
- (IBAction)btSwitchClick:(id)sender {
    BOOL isButtonOn = [_btswitch isOn];
    NSLog(@"消息切换事件");
    [DE serverCall:@"updateUsrGrpNotifyStatus" params:@{@"isNotify":isButtonOn?@"0":@"1",@"groupId":contact.mID} callback:
     ^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
         
         if (success && data && [data objectForKey:@"result"]) {
             contact.mIS_ACTIVATED = isButtonOn ? @"0" : @"1";
             NSLog(@"消息免打扰。。。%@。。。。%@",contact.mIS_ACTIVATED,contact.mID);
             [ContactDao updateContact:contact];
            /* MessageSession *mesSession = [MessageSessionDao queryMsgSessionById:[NSString stringWithFormat:@"%@_%@",MESSAGE_TYPE_P2G,groupid]];
             mesSession.isremind =  isButtonOn ? @"0" : @"1";
             [MessageSessionDao updateMessageSession:mesSession];
             */
             [self showAlerHUD:@"设置成功！"];
         }else{
             [self showAlerHUD:@"设置失败！"];
             _btswitch.on =!isButtonOn;
         }
         
     }];
    

}

//点击完成按钮事件
/////我的群，加群成员，需要别人验证，讨论组不需要；添加群成员可以重复增加
- (void) unitDoneTouched:(id)sender
{
    NSLog(@"添加群成员");
    //如果增加群成员为空，直接提示未添加群成员返回
    if(_selecteduser.count<=0)
    {
        [self showAlerHUD:@"您未新增群成员！"];
        return;
    }
    
    NSEnumerator *enumerator = [_selecteduser objectEnumerator];
    NSMutableString *ids = [[NSMutableString alloc] initWithString:@""];
    
    for (Contact *cid in enumerator) {
        [ids insertString:[NSString stringWithFormat:@"%@,",cid.mID] atIndex:0];
        NSLog(@"添加的所有群成员：%@",ids);
    }
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self removeThisSeesion];
    [DE serverCall:@"addGrpMember" params:@{@"userIds":ids,@"groupId":groupid} callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
        if (success) {
            
            NSString *addVersion = [DE getGlobalVar:[NSString stringWithFormat:@"%@_%@", [DE getGlobalVar:LOGIN_USER_REALID],[DE getGlobalVar:CONTACT_VERSION]]];
            NSDictionary *userInfo = @{@"AddressBookVersion":addVersion==nil?@"0":addVersion};
            
            [DE serverCall:@"refreshAdBook" params:userInfo callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
                
                if(success){
                    @try {
                        [DE updateLocalDBContacts:[data objectForKey:@"txl"] sessionId:nil businessId:nil sendout:YES];
                        UIAlertView *view = [[UIAlertView alloc]initWithTitle:@"提示" message:@"添加群成员成功！" delegate:self cancelButtonTitle:@"返回上一级" otherButtonTitles:nil, nil];
                        [view show];
                        
                    }
                    @catch (NSException *exception) {
                        [self showAlerHUD:@"添加群成员失败！"];
                    }
                }else{
                    [self showAlerHUD:@"添加群成员失败！"];
                }
            }];
            
        }else{
            
            UIAlertView *view = [[UIAlertView alloc]initWithTitle:@"提示" message:@"添加群成员失败！" delegate:self cancelButtonTitle:@"返回上一级" otherButtonTitles:@"确定", nil];
            [view show];
        }
        
    }];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

-(void)removeThisSeesion{
    
    NSString* sessionId =[NSString stringWithFormat:@"%@_%@",MESSAGE_TYPE_P2G,groupid];
    [MessageSessionDao deleteMessageSession:sessionId];
}

-(void)dropGroup/*:(id)sender*/
{
    NSLog(@"解散群");
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [self removeThisSeesion];
    [DE serverCall:@"dropGrp" params:@{@"groupId":groupid} callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
        
        [MBProgressHUD hideAllHUDsForView:self.view animated:NO];
        
        if (success) {
            
            NSString *addVersion = [DE getGlobalVar:[NSString stringWithFormat:@"%@_%@", [DE getGlobalVar:LOGIN_USER_REALID],[DE getGlobalVar:CONTACT_VERSION]]];
            NSDictionary *userInfo = @{@"AddressBookVersion":addVersion==nil?@"0":addVersion};
            [DE serverCall:@"refreshAdBook" params:userInfo callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
                if(success){
                    @try {
                        [DE updateLocalDBContacts:[data objectForKey:@"txl"] sessionId:nil businessId:nil sendout:YES];
                        UIAlertView *aler =  [[UIAlertView alloc] initWithTitle:@"提示" message:@"解散群组成功！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                       [aler show];
                    }
                    @catch (NSException *exception) {
                        [self showAlerHUD:@"解散群组成功:本地更新失败！"];
                    }
                    
                }else{
                    [self showAlerHUD:@"解散群组成功：服务器同步失败！"];
                    
                }
                
            }];
            
        }else{
            
            [self showAlerHUD:@"解散群组失败!"];
        }
    }];
}

-(void)QuitGroup/*:(id)sender*/
{
    
    NSLog(@"退出群");
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [self removeThisSeesion];
    [DE serverCall:@"exitGrp" params:@{@"groupId":groupid} callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
        
        [MBProgressHUD hideAllHUDsForView:self.view animated:NO];
        
        if (success) {
            
            NSString *addVersion = [DE getGlobalVar:[NSString stringWithFormat:@"%@_%@", [DE getGlobalVar:LOGIN_USER_REALID],[DE getGlobalVar:CONTACT_VERSION]]];
            NSDictionary *userInfo = @{@"AddressBookVersion":addVersion==nil?@"0":addVersion};
            [DE serverCall:@"refreshAdBook" params:userInfo callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
                if(success){
                    @try {
                        [DE updateLocalDBContacts:[data objectForKey:@"txl"] sessionId:nil businessId:nil sendout:YES];
                        UIAlertView *aler =  [[UIAlertView alloc] initWithTitle:@"提示" message:@"退出群组成功！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                        [aler show];
                        
                    }
                    @catch (NSException *exception) {
                        [self showAlerHUD:@"退出群组成功:本地更新失败！"];
                    }
                    
                }else{
                    [self showAlerHUD:@"退出群组成功：服务器同步失败！"];
                    
                    
                }
                
            }];
            
        }else{
            
            //[self showAlerHUD:@"退出群组失败!"];
            [self showAlerHUD:desc];
        }
    }];

}

- (void)viewWillAppear:(BOOL)animated
{
    //
    NSLog(@"刷新界面");
    [super viewWillAppear:animated];
    [_groupUser removeAll];
    for( Contact * contact0 in _groupuserarr)
    {
        [_groupUser addNewUnit:contact0];
    }
    //新增的成员（没有删除已经重复的）
    //
    int nAddMore = 0;
    for(Contact * conselected in _selecteduser)
    {
        BOOL baddNew = YES; //是否为新增成员
        for( Contact * contact0 in _groupuserarr)
        {
            if ([conselected.mID isEqualToString:contact0.mID]) {
                baddNew = FALSE;
                nAddMore++;
                break;
            }
        }
        if (baddNew == YES) {
            [_groupUser addNewUnit:conselected];
        }
        else
            continue;
    }
     _groupnumber.text = [[NSString alloc] initWithFormat:@"  群成员（%lu人）" ,(unsigned long)_groupuserarr.count+(unsigned long)_selecteduser.count-nAddMore];
    
    //群头像刷新
    if([_grouptype isEqualToString:TYPE_GROUP_PUTONG])//普通群
    {
        NSLog(@"更新头像。。。。。。。。。。");
        contact = [ContactDao getContactById:groupid];
        //群头像
        NSURL *url= [NSURL URLWithString: [contact.mHEAD_IMG hasPrefix:@"http"]?contact.mHEAD_IMG:[NSString stringWithFormat:@"%@%@",DE.fileEngineeUrl,contact.mHEAD_IMG]];
        [_groupImg setImageWithURL:url placeholderImage:[UIImage imageNamed:@"empty_photo"]];
        _Groupname.text = contact.mNAME;
    }
    
    //刷新标签
    NSMutableArray *listtags = [[NSMutableArray alloc]init];
    for (DataDict * i   in  _selectedLable)
    {
        [listtags addObject:i];
    }
    if ([_grouptype isEqualToString:TYPE_GROUP_PUTONG]) {
        if([sCreateUser isEqualToString:DE.userId])
            [self reSetGroupLable:listtags groupType:@"0"];
        else
            [self reSetGroupLable:listtags groupType:@"1"];
    }
    else
       [self reSetGroupLable:listtags groupType:@"1"];
}

- (void) AppleToJoinGroup{
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self removeThisSeesion];
    [DE serverCall:@"applyToJoinGrp" params:@{@"groupId":groupid} callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
        if (success) {
            [DE updateLocalDBContacts:[data objectForKey:@"txl"] sessionId:nil businessId:nil sendout:YES];
            UIAlertView *view = [[UIAlertView alloc]initWithTitle:@"提示" message:@"申请入群成功！" delegate:self cancelButtonTitle:@"返回上一级" otherButtonTitles:nil, nil];
           [view show];
        }
        else{
            UIAlertView *view = [[UIAlertView alloc]initWithTitle:@"提示" message:@"申请入群失败！" delegate:self cancelButtonTitle:@"返回上一级" otherButtonTitles:@"确定", nil];
            [view show];
        }
    }];
}

//点确定按钮事件（暂时处理一样，回到通讯录主页）
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
   if(alertView.tag==111) //解散群
   {
       if(buttonIndex==1)
           [self dropGroup];
   }
   else  if(alertView.tag==112)//退群
   {
       if(buttonIndex==1)
          [self QuitGroup];
   }
   else
   {
       kAppDelegate.needRefrsh=YES;
       [kAppDelegate.iCSDrawerController.navigationController popToRootViewControllerAnimated:YES];
   }
    
}
- (IBAction)btOperateClick:(id)sender {
    UIButton *button = (UIButton *)sender;
    if(button.tag==101)//解散群
    {
        NSLog(@"解散群");
        //20150820 优化增加二次确认
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您确定解散当前群吗？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        alert.tag = 111;
        [alert show];
        
    }
    else if(button.tag==102)
    {
         NSLog(@"退群");
        //20150820优化增加二次确认
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您确定退出当前群吗？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        alert.tag = 112;
        [alert show];
    }
    else if(button.tag == 103)
    {
        NSLog(@"申请入群");
        [self AppleToJoinGroup];
    }
    
}

//重写提示效果(个性化)
-(void)showAlerHUD:(NSString*)text
{
   BDKNotifyHUD * hudex = [[BDKNotifyHUD alloc] initWithImage:[UIImage imageNamed:@""]  text:text];
    hudex.center = CGPointMake(self.view.center.x, _btOperate.frame.origin.y+120);
    [self.view addSubview:hudex];
    [hudex presentWithDuration:1.5 speed:0.5f inView:self.view completion:^{
        [hudex removeFromSuperview];
    }];
}

-(void)viewDidUnload
{
    [super viewDidUnload];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:CONTACT_CHANGE_BROADCAST object:nil];
}

@end
